/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.utils {
	
	import lads.flad.load.LoadManager;
	import lads.flad.sound.SoundManager;
	import lads.flad.sound.SoundObject;
	
	/**
	 * AudioXMLParser: parses engineDJW audio nodes to sound manager after load
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class AudioXMLParser {
		
		static public function parse($xml:XML, $loadManager:LoadManager, $soundManager:SoundManager, $path:String = null):void {
			var node:XML;			
			var trackChannels:int;
			var trackFade:Number;
			var trackVolume:Number;
			var trackLoops:Boolean;			
			$path = $path || "";
			
			// add sound tracks to sound manager (think multitrack tracks)
			for each(node in $xml..track) {
				trackChannels = int(node.@channels);
				trackFade = Number(node.@crossfade);
				trackVolume = Number(node.@volume);
				if (trackChannels == 0) trackChannels = -1;
				if (trackVolume == 0) trackVolume = 1;
				$soundManager.addTrack(String(node.@name), trackChannels, trackFade, trackVolume);
			}			
			
			// add groups to sound manager (group is a bunch of samples, triggered at random)
			for each(node in $xml..group)
				$soundManager.addGroup(String(node.@name));
			
			// add sounds to sound manager
			var trackName:String;
			var sound:SoundObject;
			var urlOrSound:Object;
			for each(node in $xml..sound) {
				trackName = getTrackName(node);
				if (node.@streaming == "true")
					urlOrSound = $path + String(node.@file);
				else urlOrSound = $loadManager.getSound(node.@name);
				sound = $soundManager.addSound(new SoundObject(node.@name, urlOrSound, 1, String(node.@looping) == "true"), trackName);
				if (node.parent().name() == "group")
					$soundManager.addSoundToGroup(sound, node.parent().@name);
			}
		}
		
		static private function getTrackName($node:XML):String {
			var parent:XML = $node.parent();
			while (parent) {
				if (parent.name() == "track")
					return parent.@name;
				parent = parent.parent();
			}
			return "default";
		}
		
	}

}